<template>
    <div>
        <a-modal
            title="关联预发布版本"
            centered
            v-model:visible="visible"
            :confirm-loading="loading"
            width="70vw"
            :bodyStyle="{ padding: 0, height: '70vh' }"
            @cancel="handleCancel"
        >
            <div style="height: 100%; padding: 12px">
                <a-transfer
                    :data-source="list"
                    show-search
                    :target-keys="targetKeys"
                    :filter-option="(inputValue, item) => item.versionNumber.indexOf(inputValue) !== -1"
                    @change="handleChange"
                    v-if="visible"
                >
                    <template #children="{ filteredItems, selectedKeys, disabled: listDisabled, onItemSelectAll, onItemSelect }">
                        <a-table
                            :scroll="{ y: 'calc(70vh - 120px)' }"
                            :row-selection="
                                getRowSelection({
                                    disabled: listDisabled,
                                    selectedKeys,
                                    onItemSelectAll,
                                    onItemSelect
                                })
                            "
                            :showHeader="false"
                            :columns="columns"
                            :data-source="filteredItems"
                            size="small"
                            :style="{ pointerEvents: listDisabled ? 'none' : null }"
                            :custom-row="
                                ({ key, disabled: itemDisabled }) => ({
                                    onClick: () => {
                                        if (itemDisabled || listDisabled) return;
                                        onItemSelect(key, !selectedKeys.includes(key));
                                    }
                                })
                            "
                        >
                            <template #description="{ record }">
                                <HToolTip :title="record.description">
                                    <span>{{ record.description }}</span>
                                </HToolTip>
                            </template>
                        </a-table>
                    </template>
                </a-transfer>
            </div>

            <template #footer>
                <flexbox justify="flex-end" class="btn-group">
                    <a-button @click="handleCancel">取消</a-button>
                    <a-button type="primary" class="margin-l-8" @click="handleSave" :disabled="!targetKeys.length">确认</a-button>
                </flexbox>
            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { difference } from 'lodash-es';
import api from '@/api';
import { message } from 'ant-design-vue';
import { defineComponent, reactive, ref, toRefs, onDeactivated } from 'vue';
import { HToolTip } from '@/components';
export default defineComponent({
    components: {
        HToolTip
    },
    props: {
        lubiaoDetail: {
            type: Object,
            default: () => ({})
        },
        subVersionInfo: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const ruleFormRef = ref<any>();
        const state = reactive<any>({
            visible: false,
            loading: false,
            columns: [
                { title: '版本号', width: 100, dataIndex: 'versionNumber' },
                { title: '版本名称', dataIndex: 'description', ellipsis: true, slots: { customRender: 'description' } }
            ],
            list: [],
            targetKeys: [],
            targetItems: [],
            versionNumber: ''
        });
        const open = () => {
            state.targetKeys = [];
            state.targetItems = [];
            getVersionOptions();
            state.visible = true;
        };
        const getVersionOptions = async () => {
            const query = {
                type: 3,
                catalogCode: props.subVersionInfo.catalogCode,
                versionNumber: state.versionNumber,
                excludeParentId: props.subVersionInfo.id
            };
            const { success, moule } = await api.versionControlModel.getVersionByCondition(query);
            if (success) {
                state.list = [...moule].map((item) => ({
                    ...item,
                    description: item.description || '',
                    key: item.id.toString()
                }));
            }
        };
        const handleSave = async () => {
            state.loading = true;
            const query = state.targetItems.map((item) => ({
                ...item,
                parentId: props.subVersionInfo.id
            }));
            const { success, errorMsg } = await api.versionControlModel.batchSave(query);
            if (success) {
                emit('success');
                state.visible = false;
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };
        const handleCancel = () => {
            state.visible = false;
        };

        const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
            return {
                getCheckboxProps: (item: Record<string, string | boolean>) => ({
                    disabled: disabled || item.disabled
                }),
                onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
                    const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key);
                    const diffKeys = selected ? difference(treeSelectedKeys, selectedKeys) : difference(selectedKeys, treeSelectedKeys);
                    onItemSelectAll(diffKeys, selected);
                },
                onSelect({ key }: Record<string, string>, selected: boolean) {
                    onItemSelect(key, selected);
                },
                selectedRowKeys: selectedKeys
            };
        };

        const handleChange = (nextTargetKeys) => {
            state.targetKeys = nextTargetKeys;
            state.targetItems = state.list.filter((item) => state.targetKeys.includes(item.key));
            console.log(state.targetItems);
        };
        // 销毁时关闭弹窗
        onDeactivated(() => {
            state.visible = false;
        });
        return {
            ruleFormRef,
            ...toRefs(state),
            open,
            handleSave,
            handleCancel,
            getRowSelection,
            handleChange
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.ant-transfer) {
    height: 100%;
}
::v-deep(.ant-transfer-list) {
    width: calc(50% - 20px);
    height: 100%;
}

// 自定义表格高度，保持高度自适应
::v-deep(.ant-table-body) {
    height: calc(70vh - 170px) !important;
}
::v-deep(.ant-table-empty .ant-table-body) {
    height: auto !important;
}
</style>